<script setup>
import dayjs from 'dayjs'
import { v4 as uuidv4 } from 'uuid'
import ExcelUtils from '@/utils/fileReader'
import { fileListUpload } from '@/api/subject/subject'
const { proxy } = getCurrentInstance()
const route = useRoute()

const { sys_pneumatic_column } = proxy.useDict('sys_pneumatic_column')
const emit = defineEmits(['onSuccess'])
const props = defineProps({
  workType: {
    type: String,
    default: ''
  },
  projectId: {
    type: String,
    default: 0
  }
})

const visible = ref(false)
const fileList = ref([])
const title = ref('文件上传')
const showDlg = () => {
  console.log('sdddd')
  visible.value = true
}
const uploadSuccess = () => {
  proxy.$message.success('上传成功')
  emit('onSuccess')
  visible.value = false
  fileList.value = []
}

const getUploadData = (file) => {
  const fileNameArr = file.name.split('.')
  const currentFileType = fileNameArr[fileNameArr.length - 1] // 使用局部变量
  const currentFileRaw = file.raw
  if (currentFileType === 'xlsx' || currentFileType === 'xlsm' || currentFileType === 'xlsx') {
    return ExcelUtils.parseExcelFile(currentFileRaw)
      .then(({ headers, tableData }) => {
        const id = uuidv4()
        const keyMap = handleDict(sys_pneumatic_column.value)
        const transData = transformedData(tableData, keyMap, id)
        return {
          id,
          fileType: currentFileType,
          projectId: props.projectId,
          workType: props.workType,
          timeStamp: dayjs().unix(),
          fileData: JSON.stringify(transData)
        }
      })
      .catch((error) => {
        console.error('解析 Excel 文件失败:', error)
      })
    // 处理dat文件格式
  } else if (currentFileType === 'dat') {
    return ExcelUtils.parseDatFile(currentFileRaw).then(({ experimentData, resultData }) => {
      const id = uuidv4()
      // 获取数据字典{key: value}
      const keyMap = sys_pneumatic_column.value.reduce((acc, item) => {
        acc.set(item.value, item.label)
        return acc
      }, new Map())
      const keyObj = Object.fromEntries(keyMap)
      const transExperimentData1 = transformedDatData(experimentData, keyObj, id)
      const transResultData2 = transformedDatData(resultData, keyObj, id)
      return {
        id,
        fileType: currentFileType,
        projectId: props.projectId,
        workType: props.workType,
        timeStamp: dayjs().unix(),
        fileData: JSON.stringify(transExperimentData1),
        resultData: JSON.stringify(transResultData2)
      }
    })
    // 处理txt文件格式
  } else if (currentFileType === 'txt') {
    return ExcelUtils.parseTxtFile(currentFileRaw).then(res => {
      const id = uuidv4()

      const keyMap = sys_pneumatic_column.value.reduce((acc, item) => {
        acc.set(item.value, item.label)
        return acc
      }, new Map())
      const keyObj = Object.fromEntries(keyMap)
      const txtData = transformedDatData(res, keyObj, id)
      return {
        id,
        fileType: currentFileType,
        projectId: props.projectId,
        workType: props.workType,
        timeStamp: dayjs().unix(),
        fileData: JSON.stringify(txtData)
      }
    })
  } else {
    return ExcelUtils.commonFile(currentFileRaw).then(res => {
      console.log(currentFileType)
      const id = uuidv4()
      return {
        id,
        fileType: currentFileType,
        projectId: props.projectId,
        workType: props.workType,
        timeStamp: dayjs().unix()
      }
    })
  }
}

const handleDict = (dict) => {
  const dictMap = {}
  dict.forEach(item => {
    dictMap[item.label] = item.value
  })
  return dictMap
}
const transformedData = (data, keyMap, fileId) => {
  const transData = data.map(item => {
    const newItem = {}
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(keyMap, key)) {
        newItem[keyMap[key]] = item[key]
      } else {
        proxy.$message.warning(`存在未定义的数据字典<${key}>,请先前往添加数据字典`)
        throw new Error(`Missing key mapping for '${key}'`)
        // newItem[key] = item[key] // 如果没有找到对应的映射键名，保留原始键名
      }
    }
    return newItem
  })
  const inputData = []
  transData.forEach((item, index) => {
    for (const key in item) {
      inputData.push({
        fileId,
        pneumaticKey: key,
        pneumaticValue: item[key],
        rowIndex: index + 1
      })
      // const pneumaticKey = key
      // const pneumaticValue = item[key]
    }
  })
  return inputData
}
const transformedDatData = (data, keyMap, fileId) => {
  const transData = data.map(item => {
    const newItem = {}
    for (const key in item) {
      if (Object.prototype.hasOwnProperty.call(keyMap, key)) {
        newItem[key] = item[key]
      } else {
        proxy.$message.warning(`存在未定义的数据字典<${keyMap[key]}>,请先前往添加数据字典`)
        throw new Error(`Missing key mapping for '${key}'`)
        // newItem[key] = item[key] // 如果没有找到对应的映射键名，保留原始键名
      }
    }
    return newItem
  })
  const inputData = []
  transData.forEach((item, index) => {
    for (const key in item) {
      inputData.push({
        fileId,
        pneumaticKey: key,
        pneumaticValue: item[key],
        rowIndex: index + 1
      })
      // const pneumaticKey = key
      // const pneumaticValue = item[key]
    }
  })
  return inputData
}
const handleChange = (file, fileList) => {
  console.log(file.size)
  fileList.value = fileList
  if (file.size / 1024 / 1024 > 10000) {
    proxy.$message.warning('文件大小不得超过100M,请重新选择')
    fileList.value.pop()
  }
}
const onExceed = (files, fileList) => {
  proxy.$message.warning('目前只支持批量上传50个文件， 请删除后再次选择！')
}
const submitUpload = async () => {
  if (fileList.value.length === 0) {
    proxy.$message.warning('请选择文件')
    return
  }

  console.log(fileList.value)

  // 收集所有上传请求
  const uploadPromises = fileList.value.map(async file => {
    console.log(file.name)
    const formData = new FormData()
    const data = await getUploadData(file)
    console.log(data)
    formData.append('file', file.raw)
    formData.append('id', data.id)
    formData.append('fileType', data.fileType)
    formData.append('projectId', data.projectId)
    formData.append('timeStamp', data.timeStamp)
    formData.append('workType', data.workType)

    if (data.fileData) {
      formData.append('fileData', data.fileData)
    }

    if (data.resultData) {
      formData.append('resultData', data.resultData)
    }

    // 处理单个文件的上传
    try {
      proxy.$modal.loading('正在上传文件，请稍候...')
      const res = await fileListUpload(formData, data.timeStamp)
      console.log(`File uploaded successfully: ${file.name}`, res)
      return res // 返回上传结果
    } catch (e) {
      console.error(`Failed to upload file: ${file.name}`, e)
      throw e // 抛出错误以便在 Promise.all 捕获
    }
  })

  // 等待所有上传完成
  try {
    await Promise.all(uploadPromises)
    proxy.$modal.closeLoading()
    uploadSuccess()
  } catch (e) {
    proxy.$modal.closeLoading()
    proxy.$message.error('部分文件上传失败')
    console.error('Upload error:', e)
  }
}
const beforeFileUpload = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 200) {
    proxy.$message.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}
defineExpose({
  showDlg
})
</script>

<template>
  <el-dialog
    :title="title"
    v-model="visible"
    width="800px"
    append-to-body
  >
    <div>
      <el-upload
        v-model:file-list="fileList"
        class="upload-demo"
        ref="upload"
        action="#"
        :limit="50"
        multiple
        :on-exceed="onExceed"
        :file-list="fileList"
        :on-change="handleChange"
        :before-upload="beforeFileUpload"
        :auto-upload="false"
      >
        <template #trigger>
          <el-button type="primary">
            选取文件
          </el-button>
        </template>
      </el-upload>
      <!--      <FileUpload
        ref="fileUpload"
        :upload-url="upload.url"
        :file-type="upload.fileType"
        :file-size="50"
        @upload-success="uploadSuccess"
        @on-change="changeFile"
        :project-id="route.params.projectId"
        :work-type="workType"
        :limit="100"
      />-->
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="submitUpload"
        >
          确认上传
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>
